package top.aicey.ai.sparring.llm.impl;

import com.alibaba.fastjson2.JSON;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import top.aicey.ai.sparring.common.constants.AIConstants;
import top.aicey.ai.sparring.dto.llm.EvaluateScoreInfo;
import top.aicey.ai.sparring.llm.ICoolLLMService;
import top.aicey.ai.sparring.llm.ILLMClientService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CoolLLMServiceImpl implements ICoolLLMService {

    @Autowired
    private Map<String,ILLMClientService> llmClientServiceMap;

    @Value("${llm.type:bailianClientService}")
    private String type;

    @Override
    public EvaluateScoreInfo generateEvaluateScoreInfo(String content, List<String> dimensionList, String userPrompt,Integer score) {

        String dimensions = Joiner.on(",").skipNulls().join(dimensionList);
        Map<String,Object> params = Maps.newHashMap();
        // 评分维度
        params.put("dimension_list",dimensions);

        // 用户prompt
        params.put("user_prompt",dimensions);

        // 总分数
        params.put("score",score);

        log.info("generateEvaluateScoreInfo request:{}",content);
        String resultContent = getClient().query(content, params);
        log.info("generateEvaluateScoreInfo response:{}",resultContent);
        if (!StringUtils.isEmpty(resultContent) && resultContent.indexOf(AIConstants.LEFT_BRACKET) > -1){
            // 从前往后找到第一个花括号{ 从后往前找到第一个花括号} 取中间的值
            resultContent = resultContent.substring(resultContent.indexOf(AIConstants.LEFT_BRACKET),resultContent.lastIndexOf(AIConstants.RIGHT_BRACKET)+1);
        }
        return JSON.parseObject(resultContent, EvaluateScoreInfo.class);
    }


    @Override
    public List<String> generateDimensions(String content, Integer count) {

        String dimensions = getClient().generateDimensions(content, count);

        if (!StringUtils.isEmpty(dimensions) && dimensions.indexOf(AIConstants.LEFT_SQUARE_BRACKETS) > -1){
            // 从前往后找到第一个中括号[ 从后往前找到第一个中括号] 取中间的值
            dimensions = dimensions.substring(dimensions.indexOf(AIConstants.LEFT_SQUARE_BRACKETS),dimensions.lastIndexOf(AIConstants.RIGHT_SQUARE_BRACKETS)+1);
        }
        return JSON.parseArray(dimensions,String.class);
    }

    private ILLMClientService getClient(){
        if ("bailianClientService".equals(type)){
            return llmClientServiceMap.get(type);
        }

        return null;
    }
}
